#include <project.h>
#include "userMain.h"
#include "userBackLight.h"

unsigned char uHumanFlag = 0;
unsigned int uHumanMarkTick = 0;
unsigned char userBackLightLevel=0;
unsigned char uBackLightCase=0;
unsigned char userBackLightLevelPre = 0xFF;
unsigned char uBackLightCasePre = 0xFF;;

extern unsigned char userLightSensorEnable;
extern unsigned char userMotionEnable;
extern unsigned char userMotionDetect;
extern unsigned char userLedLevel;
extern unsigned char userMotionDetectFlag;

//#define     BACK_LIGHT_lEVEL_MAX    25
void userBackLightLevelSetFunc(unsigned int uLigthSensorValue)
{
    userBackLightLevel = uLigthSensorValue / 100;
    if(userBackLightLevel>BACK_LIGHT_lEVEL_MAX) userBackLightLevel = BACK_LIGHT_lEVEL_MAX;
}

void userBackLightHumanSetFunc(void)
{
    if(userMotionDetectFlag)
    {
        uHumanMarkTick = 0;
    }
    else
    {
        uHumanMarkTick++;
    }
}

void userBackLightCtrlFunc(void)
{
    if(uHumanMarkTick > 10000)
    {
        if(userMotionDetect)
        {
            userMotionDetect = 0;
            userSendMotionInfoFunc();
        }
        uHumanMarkTick = 11000;
    }

    uBackLightCase = 0x00;
    if(userLightSensorEnable) uBackLightCase |= 0x01;
    if(userMotionEnable) uBackLightCase |= 0x02;
    if(userMotionDetect) uBackLightCase |= 0x04;
    if(userLedLevel) uBackLightCase |= 0x08;
    
    if((userBackLightLevel == userBackLightLevelPre)&&(uBackLightCase == uBackLightCasePre))
    {
        return;
    }
    userBackLightLevelPre = userBackLightLevel;
    uBackLightCasePre = uBackLightCase;
    switch(uBackLightCase & 0x03)
    {
        case 0x00:
        {
            userBackLedSetFunc(BACK_LIGHT_lEVEL_MAX/2);
            break;
        }
        case 0x01:
        {
            userBackLedSetFunc(userBackLightLevel);
            break;
        }
        case 0x02:
        {
            if(userMotionDetect)  userBackLedSetFunc(0xFF);
            else   userBackLedSetFunc(0x00);
            break;
        }
        case 0x03:
        {
            if(userMotionDetect) userBackLedSetFunc(userBackLightLevel);
            else     userBackLedSetFunc(0x00);
            break;
        }
        default:
        {
            break;
        }
    }
}